package com.zr.bookcorner.presenter;


import android.Manifest;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.constant.ExtraName;
import com.zh.baselibrary.model.BookModel;
import com.zh.baselibrary.model.TaskModel;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.netutils.HRetrofitNetHelper;
import com.zh.baselibrary.netutils.NetUtil;
import com.zh.baselibrary.rxjava.RxSubscribe;
import com.zh.baselibrary.utils.IntentUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.CurrentTime;
import com.zh.model.EquipmentLogin;
import com.zh.model.home.TokenBean;

import com.zr.bookcorner.BookApplication;
import com.zr.bookcorner.activity.HomeActivity;
import com.zr.bookcorner.activity.LimitActivity;
import com.zr.bookcorner.activity.QRCodeActivity;
import com.zr.bookcorner.service.HeartService;
import com.zr.bookcorner.utils.DeviceUtil;
import com.zr.bookcorner.websocket.AppResponseDispatcher;
import com.zr.websocket.WebSocketSend;
import com.zr.websocket.WebSocketService;
import com.zr.websocket.WebSocketSetting;

import org.greenrobot.eventbus.EventBus;
import org.xutils.common.util.LogUtil;

import java.util.Calendar;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

import static android.content.Context.ALARM_SERVICE;

public class LoginPresenter extends BasePresenter {
    private BookModel model;
    private boolean hasStart = false;
    EquipmentLogin equipmentLogin;
    @Override
    public void attachModel(Context context) {
        model  = new BookModel(context);

    }

    public void login(){
     //   Observable<BaseResp<TokenBean>> observable =  getObservableNotStop(model.equipmentLogin(DeviceUtil.getEquipmentLogin(getContext())));
        Observable<BaseResp<TokenBean>> observable =  getObservableNotStop(model.equipmentLogin(PhoneUtil.getUUID(getContext())));
        observable.subscribe(new RxSubscribe<BaseResp<TokenBean>>() {
            @Override
            public void onSuccess(BaseResp<TokenBean> baseResp) throws Exception {
                reportBaseInfo();
            }
            @Override
            public void onHint(String hint) {

            }
        });
    }
    private void reportBaseInfo(){
        model.reportBaseInfo(equipmentLogin)
                .subscribeOn(Schedulers.io())//启动订阅线程
                .subscribe(new RxSubscribe<BaseResp<CurrentTime>>() {
                    @Override
                    public void onSuccess(BaseResp<CurrentTime> currentTimeBaseResp) throws Exception { }
                    @Override
                    public void onHint(String hint) { }});
    }
    public void permissionCheck(){
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getContext(), Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
                != PackageManager.PERMISSION_GRANTED
        ) {
            requestEachRxPermission(Manifest.permission.READ_PHONE_STATE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
        } else {
            startHeart();
        }
    }
    private void requestEachRxPermission(String... permissions) {
        RxPermissions rxPermissions = new RxPermissions((Activity) getContext());
        rxPermissions.requestEach(permissions).subscribe((Action1<? super Permission>) permission -> {
            if (permission.granted) {
                startHeart();
            } else if (permission.shouldShowRequestPermissionRationale) {
                //拒绝权限请求
                Toast.makeText(getContext(), "已拒绝权限" + permission.name, Toast.LENGTH_SHORT).show();
            } else {
                // 拒绝权限请求,并不再询问
                // 可以提醒用户进入设置界面去设置权限
                Toast.makeText(getContext(), "已拒绝权限" + permission.name + "并不再询问", Toast.LENGTH_SHORT).show();
            }
        });

    }
    private void startHeart() {
        equipmentLogin = new EquipmentLogin("0",PhoneUtil.getUUID(getContext()),PhoneUtil.getLocalVersion(getContext()),"v"+PhoneUtil.getVersionName(getContext()));
        new Thread(new Runnable() {
            @Override
            public void run() {
                equipmentLogin = DeviceUtil.getEquipmentLogin(getContext());
            }
        }).start();
        if (NetUtil.checkNetwork( getContext()) == NetUtil.NO_NETWORK) {
            ToastView.showLong("网络无法访问，请检查网络连接");
        } else {
            if(!hasStart) {
                hasStart = true;
                String uuId = PhoneUtil.getUUID( getContext());
                WebSocketSetting.setConnectUrl(HRetrofitNetHelper.getWebSocketUrl()+ uuId);//必选
                WebSocketSetting.setResponseProcessDelivery(new AppResponseDispatcher( getContext()));
                WebSocketSetting.setReconnectWithNetworkChanged(true);
                //启动 WebSocket 服务
                LogUtils.e("qidong"+HRetrofitNetHelper.getWebSocketUrl()+ uuId);
                ShareManager.setValue(getContext(),"websocket",HRetrofitNetHelper.getWebSocketUrl()+ uuId);
                getContext().startService(new Intent( getContext(), WebSocketService.class));
                EventBus.getDefault().post(new WebSocketSend("","set"));

            }
        }
        startHome();
    }
    private void startHome() {
        TTSUtils.getInstance().init(BookApplication.getContext());
        Long deadLine = ShareManager.getLong(getContext(), BaseConstant.AUTHORIZATION_DEADLINE_BOOK);
        int lockStatus = ShareManager.getInt(getContext(), BaseConstant.DEVICE_LOCK_TYPE);
        if (lockStatus == 1) {
            Bundle bundle = new Bundle();
            bundle.putInt(ExtraName.KEY_DATA,2);
            getContext().stopService(new Intent(getContext(), HeartService.class));
            getContext().startService(new Intent(getContext(), HeartService.class));
            IntentUtils.instance().startActivity(getContext(), LimitActivity.class,bundle);
            login();
        } else {
            if (deadLine == null||deadLine == 0 || deadLine == -1) {
                IntentUtils.instance().startActivity(getContext(), QRCodeActivity.class);
            } else {
                getContext().stopService(new Intent(getContext(), HeartService.class));
                getContext().startService(new Intent(getContext(), HeartService.class));
                IntentUtils.instance().startActivity(getContext(), HomeActivity.class);
                login();
            }
        }
        ((Activity)getContext()).finish();
    }

}
